<?php
/**
 *	  [Haidao] (C)2013-2099 Dmibox Science and technology co., LTD.
 *	  This is NOT a freeware, use is subject to license terms
 *
 *	  http://www.haidao.la
 *	  tel:400-600-2042
 */
class AdminTradeLogController extends AdminBaseController {
	/**
	 * 自动执行
	 */
	public function _initialize() {
		parent::_initialize(); 
		$this->db = model('UserTrade');
	}



	/**
	 * 点对点交易列表
	 */   
	public function index() {
		if (IS_POST) {
			if ($_GET['keyword']) {
				$map = array();
				$map['username'] = array('LIKE',"%".trim($_GET['keyword'])."%");
				$ids = model('user')->where($map)->getField('id',TRUE);
				$sqlmap['user_id|sell_id'] = array('IN',$ids);
				
			}
			if($_GET["start"]!="" or $_GET["end"]!=""){
				$start = strtotime($_GET['start'].' 00:00:00');
				$end = strtotime($_GET['end'].' 23:59:59');
				$sqlmap['hb.update_time'] =array('between',[date('Y-m-d H:i:s',$start),date('Y-m-d H:i:s',$end)]);
			}
		
			if($_GET['status']){
				$sqlmap['hb.status'] = $_GET['status'];
			}
			$data = array();
			$data['status'] = array(
				array(
					'id'=>1,
					'name'=>'待匹配'
				),
				array(
					'id'=>2,
					'name'=>'待付款'
				),
				array(
					'id'=>3,
					'name'=>'待确认'
				),
				array(
					'id'=>4,
					'name'=>'交易成功'
				),
				array(
					'id'=>5,
					'name'=>'订单取消'
				),
			);
			foreach($data['status'] as $key => $value){
				if($value['id'] == $_GET['status']) $data['status'][$key]['selected'] = true;
			}
			$_GET['pagenum'] = isset($_GET['page']) ? intval($_GET['page']) : 1;
			$_GET['rowsnum'] = isset($_GET['rows']) && (int)($_GET['rows']) != 0 ? intval($_GET['rows']) : PAGE_SIZE;
			$data['total'] = (int) M('hang_buy')->where($sqlmap)->count();
			$data['rows'] = M('hang_buy hb')
						  ->join("__USER__ a on a.id=hb.user_id")
						  ->join("__USER__ b on b.id=hb.sell_id")
						  ->where($sqlmap)
						  ->field('hb.*,a.username as buy_username,b.username as sell_username')
						  ->limit(($_GET['pagenum']-1)*$_GET['rowsnum'].','.$_GET['rowsnum'])
						  ->select();
			$data['rows'] = !is_array($data['rows']) ? array() : $data['rows'];
			echo json_encode($data);
		}else {
			include $this->admin_tpl('admin_trade_log');
		}
	}


	/**
	 * 实时统计
	 * @return [type] [description]
	 */
	public function count(){

			$sqlmap = array();
			if($_GET["start_time"]!="" or $_GET["end_time"]!=""){
					$start = strtotime($_GET['start_time'].' 00:00:00');
					$end = strtotime($_GET['end_time'].' 23:59:59');
					$sqlmap['dateline'] =array('between',$start.','.$end);
			}
			$sqlmap['sell_id'] = array("gt",0);
			$sell_count = M("user_trade")->where($sqlmap)->count();
			unset($sqlmap['sell_id']);
			$sqlmap['user_id'] = array("gt",0);
			$buy_count = M("user_trade")->where($sqlmap)->count();
			unset($sqlmap['user_id']);
			$sqlmap['order_status'] = array("eq",3);
			$fee_sum = M("user_trade")->where($sqlmap)->sum("fee");


			$_day = date('Y-m-d');
			$tdmap = array();
			$tdmap['status'] = 3;
            $tdmap['_string'] = "DATE_FORMAT(FROM_UNIXTIME(confi_time),'%Y-%m-%d') = '".$_day."'";
            $today_fee = (float)M("user_trade")->where($tdmap)->sum('fee');
	
			// 计算 对应等级的的手续费
			$today_fee2 = bcmul($today_fee,0.3,4);
			$today_fee3 = bcmul($today_fee,0.25,4);
			$today_fee4 = bcmul($today_fee,0.15,4);
			$today_fee5 = bcmul($today_fee,0.1,4);
			$counts = M("user")->field("user_type,count(id) as count")->group("user_type")->where("user_type>1")->select();
			foreach ($counts as $key => $value) {
				if($value['user_type']==2){
					$counts[$key]['today_fee'] = $today_fee2;
					$counts[$key]['fee'] = bcdiv($today_fee2,$value['count'],4);
				}
				if($value['user_type']==3){
					$counts[$key]['today_fee'] = $today_fee3;
					$counts[$key]['fee'] = bcdiv($today_fee3,$value['count'],4);
				}
				if($value['user_type']==4){
					$counts[$key]['today_fee'] = $today_fee4;
					$counts[$key]['fee'] = bcdiv($today_fee4,$value['count'],4);
				}
				if($value['user_type']==5){
					$counts[$key]['today_fee'] = $today_fee5;
					$counts[$key]['fee'] = bcdiv($today_fee5,$value['count'],4);
				}		
			}

// p($counts);
		include $this->admin_tpl('admin_trade_count');
	}
	/**
	 * 投诉
	 */   
	public function oil() {
		if (IS_POST) {
			if ($_GET['keyword']) {
				$map = array();
				$map['username|real_name'] = array('LIKE',"%".trim($_GET['keyword'])."%");
				$ids = model('user')->where($map)->getField('id',TRUE);
				$sqlmap['a.id'] = array('IN',$ids);
				
			}
			if($_GET["start"]!="" or $_GET["end"]!=""){
				$start = strtotime($_GET['start'].' 00:00:00');
				$end = strtotime($_GET['end'].' 23:59:59');
				$sqlmap['hb.add_time'] =array('between',date('Y-m-d H:i:s',$start).','.date('Y-m-d H:i:s',$end));
			}
			if($_GET['status']){
				$sqlmap['hb.status'] = $_GET['status'];
			}
			$data = array();
			$data['status'] = array(
				array(
					'id'=>1,
					'name'=>'发起申请'
				),
				array(
					'id'=>2,
					'name'=>'成功'
				),
				array(
					'id'=>3,
					'name'=>'驳回'
				),
			);
			foreach($data['status'] as $key => $value){
				if($value['id'] == $_GET['status']) $data['status'][$key]['selected'] = true;
			}
			$_GET['pagenum'] = isset($_GET['page']) ? intval($_GET['page']) : 1;
			$_GET['rowsnum'] = isset($_GET['rows']) && (int)($_GET['rows']) != 0 ? intval($_GET['rows']) : PAGE_SIZE;
			
			$result = M('goods_buy_records hb')
						  ->join("__USER__ a on a.id=hb.user_id")
						  ->where($sqlmap)
						  ->field('hb.*,a.real_name')
						  ->limit(($_GET['pagenum']-1)*$_GET['rowsnum'].','.$_GET['rowsnum'])
						  ->select();
			$result = is_array($result) ? $result : array();
			// $data['total'] = count($data['rows']) ? count($data['rows']) : 0;
			$data['rows'] = $result;
			echo json_encode($data);
		}else {
			include $this->admin_tpl('admin_trade_oil');
		}
	}	
    /**
     * 话费充值列表
     */
    public function mobile_fare(){
        if (IS_POST) {
			if ($_GET['keyword']) {
				$map = array();
				$map['username|real_name'] = array('LIKE',"%".trim($_GET['keyword'])."%");
				$ids = model('user')->where($map)->getField('id',TRUE);
				$sqlmap['a.id'] = array('IN',$ids);
				
			}
			if($_GET["start"]!="" or $_GET["end"]!=""){
				$start = strtotime($_GET['start'].' 00:00:00');
				$end = strtotime($_GET['end'].' 23:59:59');
				$sqlmap['hb.add_time'] =array('between',date('Y-m-d H:i:s',$start).','.date('Y-m-d H:i:s',$end));
			}
			if($_GET['status']){
				$sqlmap['hb.status'] = $_GET['status'];
			}
			$data = array();
			$data['status'] = array(
				array(
					'id'=>1,
					'name'=>'发起充值'
				),
				array(
					'id'=>2,
					'name'=>'成功'
				),
				array(
					'id'=>3,
					'name'=>'驳回'
				),
			);
			foreach($data['status'] as $key => $value){
				if($value['id'] == $_GET['status']) $data['status'][$key]['selected'] = true;
			}
			$_GET['pagenum'] = isset($_GET['page']) ? intval($_GET['page']) : 1;
			$_GET['rowsnum'] = isset($_GET['rows']) && (int)($_GET['rows']) != 0 ? intval($_GET['rows']) : PAGE_SIZE;
			
			$result = M('mobile_fare_records hb')
						  ->join("__USER__ a on a.id=hb.user_id")
						  ->where($sqlmap)
						  ->field('hb.*,a.username,a.real_name')
						  ->limit(($_GET['pagenum']-1)*$_GET['rowsnum'].','.$_GET['rowsnum'])
						  ->select();
			$result = is_array($result) ? $result : array();
			// $data['total'] = count($data['rows']) ? count($data['rows']) : 0;
			$data['rows'] = $result;
			// var_dump($result);
			echo json_encode($data);
		}else {
			include $this->admin_tpl('mobile_fare');
		}
	}
	
	//审核充值话费
	public function checks_mobile()
	{
		if(IS_POST){
			$param = I('post.');
			if($param['status'] == 3 && !$param['remarks']){
				showmessage('请填写驳回原因');
			}
			$param['add_time'] = date('Y-m-d H:i:s');
			if($param['status'] == 2) unset($param['remarks']);
			try{
				M('mobile_fare_records')->save($param);
			}catch(\Exception $e){
				showmessage($e->getMessage());
			}
			showmessage('操作成功');
		}else{
			showmessage('非法操作');
		}
	}

	//审核充值加油卡
	public function checks_oil()
	{
		if(IS_POST){
			$param = I('post.');
			if($param['status'] == 3 && !$param['remarks']){
				showmessage('请填写驳回原因');
			}
			$param['update_time'] = date('Y-m-d H:i:s');
			if($param['status'] == 2) unset($param['remarks']);
			try{
				if($param['status'] == 3){
					$info =	M('goods_buy_records')->where(['id'=>$param['id']])->find();
					$user_info = M('user')->where(['id'=>$info['goods_id']])->field('upvaluation,freeze_upvaluation')->find();
					$data = [
						'upvaluation'=>$user_info['upvaluation'] + $info['price'],
						'freeze_upvaluation'=>($user_info['freeze_upvaluation'] - $info['price']) ? ($user_info['freeze_upvaluation'] - $info['price']) : 0,
					];
					M('user')->where(['id'=>$info['user_id']])->save($data);
					$data1 = [
						'user_id'=>$info['user_id'],
						'balance'=>$info['price'],
						'type'=>1,
						'add_time'=>date('Y-m-d H:i:s'),
						'remarks'=>$info['goods_remarks'].'后台驳回',
					];
					M('upvaluation_exchange_records')->add($data1);
				}
				M('goods_buy_records')->save($param);
			}catch(\Exception $e){
				showmessage($e->getMessage());
			}
			showmessage('操作成功');
		}else{
			showmessage('非法操作');
		}
	}


    /**
     * 反馈回复
     */
    public function reply()
    {
        $reply = trim(I('reply'));
        $id = I('id');
        if (empty($reply)) showmessage('输入回复内容');
        $data = array(
            'id'=>$id,
            'reply'=>$reply,
            'is_reply'=>1,
            'replytime'=>NOW_TIME,
        );
        $res = model('user_feedback')->save($data);
        if($res){
            showmessage('回复成功', U('tradelog/feedback'), 1);
        }else{
            showmessage('回复失败');
        }
	}
	//后台操作奖池
    public function union(){
        if(IS_POST){    	
			$_GET['pagenum'] = isset($_GET['page']) ? intval($_GET['page']) : 1;
			$_GET['rowsnum'] = isset($_GET['rows']) && (int)($_GET['rows']) != 0 ? intval($_GET['rows']) : PAGE_SIZE;
	    	$result = M("union cc")
	    	->field("cc.*,a.username as username")
	    	->join("__USER__ a on a.id=cc.user_id")
	    	->where($sqlmap)->order('id DESC')
	    	->limit(($_GET['pagenum']-1)*$_GET['rowsnum'].','.$_GET['rowsnum'])
	    	->select();
			$data = array();
			$data['total'] = (int) M("union")->where($sqlmap)->count();	//计算总数
			$data['rows']  = (array) $result;
			// $bla_config = C('bla_config');
			// $site_msg_type = array();
			// foreach ($bla_config as $key => $value) {
			// 	$terms['id'] = $key;
			// 	$terms['name'] = $value;
			// 	$site_msg_type[] = $terms;
			// 	unset($terms);
			// }
			// $data['msg_type'] = $site_msg_type;
			$data['search']['type_txt'] = isset($_GET['msgtype']) ? $_GET['msgtype'] :'';
			echo json_encode($data);
		}else {
			include $this->admin_tpl('admin_trade_union');
		}    	
    }
    public function unionset(){
	    $id = $_GET['id'];
	    $status = $_GET['at'];
	    $msg = $_GET['msg'];
	    $info = M("union")->find($id);
	    if($info['union_status']!=0) showmessage('审核失败！');
	    $user = M("user")->find($info['user_id']);
	    // 驳回
	    if($status==2){
			$save = array();
			$save['id'] = $info['id']; 
			$save['union_status'] = 2;
			$save["deal_user"]=ADMIN_ID;
			$save["deal_info"]=$msg;
			$save['deal_time'] = NOW_TIME;
			$rut = M("union")->save($save);
	    	if($rut){
	    		showmessage('操作成功！');
	    	}else{
	    		showmessage('操作失败！');
	    	}
	    }
	    if($status==1){
			M()->startTrans();
			// 认证状态
			$save = array();
			$save['id'] = $info['id']; 
			$save['union_status'] = 1;
			$save["deal_user"]=ADMIN_ID;
			$save["deal_info"]=$msg;
			$save['deal_time'] = NOW_TIME;
			$rut = M("union")->save($save);
			$rut1 = M("user")->where("id=".$user['id'])->setField("is_union",1);
	    	if($rut!==false && $rut1!==false){
	    		M()->commit();
	    		showmessage('操作成功！');
	    	}else{
	    		M()->rollback();
	    		showmessage('操作失败！');
	    	}
	    }
    }
	private function DownloadCSV($selectObject,$head){
		$fileName=time();
		if ( !is_object( $selectObject ) || !is_array( $head ) ) {
			exit('参数错误!');
		}
		set_time_limit(0);
		//下载头.
		header ('Content-Type: application/vnd.ms-excel;charset=gbk');
		header ('Content-Disposition: attachment;filename="'.$fileName.'.csv"');
		header ('Cache-Control: max-age=0');
		//输出流;
		$file = 'php://output';
		$fp = fopen ( $file, 'a' );
		function changCode( $changArr ) {
			// 破Excel2003中文只支持GBK编码;
			foreach ( $changArr as $k => $v ) {
				$changArr [$k] = iconv ( 'utf-8', 'gbk', $v );
			}
			//返回一个 索引数组;
			return array_values( $changArr );
		};
		//写入头部;
		fputcsv ( $fp, changCode( $head ) );
		//写入数据;
		$pageSize = 100;//每次查询一百条;
		$page  = 1;//起始页码;
		$list = array();
		//查库;
		$money_type=C("SILVER_TYPE");
		$cloneObj = clone $selectObject;//因为thinkphp内部执行完select方法后会清空对象属性,所以clone;
		while ( $list = $cloneObj ->limit( $pageSize*( ($page++)-1 ), $pageSize )->select()  ) {
			$cloneObj = clone $selectObject;
			//对查询结果二次处理
			foreach ( $list as $key => $value ) {
				$value['dateline']= date('Y-m-d H:i',$value['dateline']); 
				$value['username'] = get_nickname($value['user_id']);
				$value['type'] = $money_type[$value["type"]];
				$value = array_intersect_key( $value, $head );//返回需要写入CSV的数据;
				$value = array_merge( $head, $value );//利用此函数返回需要的顺序;
				$value = changCode( $value );
				fputcsv ( $fp, $value );//写入数据;
				flush();
			}
			ob_flush();
		}
		exit();
	}


	//GF变动列表
	public function upvaluation1(){

		if(IS_POST){
			if ($_GET['keyword']) {
				$map = array();
				$map['username'] = array('LIKE',"%".trim($_GET['keyword'])."%");
				$ids = model('user')->where($map)->getField('id',TRUE);
				$sqlmap['hb.user_id'] = array('IN',$ids);
				
			}
			if($_GET["start"]!="" or $_GET["end"]!=""){
				$start = strtotime($_GET['start'].' 00:00:00');
				$end = strtotime($_GET['end'].' 23:59:59');
				$sqlmap['hb.add_time'] =array('between',[date('Y-m-d H:i:s',$start),date('Y-m-d H:i:s',$end)]);
			}
		
			if($_GET['status']){
				$sqlmap['hb.type'] = $_GET['status'];
			}
			$data = array();
			$data['status'] = array(
				//1:回收 2:兑换3：交易（冻结或返还） 4：分红 5：中奖 6：邀请获取7：后台操作 8:投注
				array(
					'id'=>1,
					'name'=>'回收'
				),
				array(
					'id'=>2,
					'name'=>'兑换'
				),
				array(
					'id'=>3,
					'name'=>'交易'
				),
				array(
					'id'=>4,
					'name'=>'分红获利'
				),
				array(
					'id'=>5,
					'name'=>'中奖获利'
				),
				array(
					'id'=>6,
					'name'=>'邀请获利'
				),
				array(
					'id'=>7,
					'name'=>'后台操作'
				),
				array(
					'id'=>8,
					'name'=>'投注'
				),
			);
			foreach($data['status'] as $key => $value){
				if($value['id'] == $_GET['status']) $data['status'][$key]['selected'] = true;
			}
			$_GET['pagenum'] = isset($_GET['page']) ? intval($_GET['page']) : 1;
			$_GET['rowsnum'] = isset($_GET['rows']) && (int)($_GET['rows']) != 0 ? intval($_GET['rows']) : PAGE_SIZE;
			$data['total'] = (int) M('hang_buy')->where($sqlmap)->count();
			$data['rows'] = M('upvaluation_exchange_records hb')
						  ->join("__USER__ a on a.id=hb.user_id")
						  ->where($sqlmap)
						  ->field('hb.*,a.username')
						  ->limit(($_GET['pagenum']-1)*$_GET['rowsnum'].','.$_GET['rowsnum'])
						  ->select();
			$data['rows'] = !is_array($data['rows']) ? array() : $data['rows'];
			echo json_encode($data);
		}else{
			include $this->admin_tpl('upvaluation1');
		}
		
	}
	//GF回收
	public function upvaluation2(){
		if(IS_POST){
			if ($_GET['keyword']) {
				$map = array();
				$map['username'] = array('LIKE',"%".trim($_GET['keyword'])."%");
				$ids = model('user')->where($map)->getField('id',TRUE);
				$sqlmap['hb.user_id'] = array('IN',$ids);
				
			}
			if($_GET["start"]!="" or $_GET["end"]!=""){
				$start = strtotime($_GET['start'].' 00:00:00');
				$end = strtotime($_GET['end'].' 23:59:59');
				$sqlmap['hb.add_time'] =array('between',[date('Y-m-d H:i:s',$start),date('Y-m-d H:i:s',$end)]);
			}
		
			if($_GET['status']){
				$sqlmap['hb.status'] = $_GET['status'];
			}
			if($_GET['type']){
				$sqlmap['hb.type'] = $_GET['type'];
			}
			$data = array();
			$data['status'] = array(
				//1:回收 2:兑换3：交易（冻结或返还） 4：分红 5：中奖 6：邀请获取7：后台操作 8:投注
				array(
					'id'=>1,
					'name'=>'已发起待确认'
				),
				
				array(
					'id'=>2,
					'name'=>'已确认'
				),
				array(
					'id'=>3,
					'name'=>'已驳回'
				),
				
			);
			foreach($data['status'] as $key => $value){
				if($value['id'] == $_GET['status']) $data['status'][$key]['selected'] = true;
			}
			$data['type'] = array(
				//1:回收 2:兑换3：交易（冻结或返还） 4：分红 5：中奖 6：邀请获取7：后台操作 8:投注
				array(
					'id'=>1,
					'name'=>'支付宝'
				),
				array(
					'id'=>2,
					'name'=>'银行卡'
				),

				
			);
			foreach($data['type'] as $key => $value){
				if($value['id'] == $_GET['type']) $data['type'][$key]['selected'] = true;
			}
			$_GET['pagenum'] = isset($_GET['page']) ? intval($_GET['page']) : 1;
			$_GET['rowsnum'] = isset($_GET['rows']) && (int)($_GET['rows']) != 0 ? intval($_GET['rows']) : PAGE_SIZE;
			$data['total'] = (int) M('hang_buy')->where($sqlmap)->count();
			$data['rows'] = M('huishou_records hb')
						  ->join("__USER__ a on a.id=hb.user_id")
						  ->where($sqlmap)
						  ->field('hb.*,a.username')
						  ->limit(($_GET['pagenum']-1)*$_GET['rowsnum'].','.$_GET['rowsnum'])
						  ->order('hb.id desc')
						  ->select();
			$data['rows'] = !is_array($data['rows']) ? array() : $data['rows'];
			echo json_encode($data);
		}else{
			include $this->admin_tpl('upvaluation2');
		}
	}
	//余额变动列表
	public function balance1(){
		if(IS_POST){
			if ($_GET['keyword']) {
				$map = array();
				$map['username'] = array('LIKE',"%".trim($_GET['keyword'])."%");
				$ids = model('user')->where($map)->getField('id',TRUE);
				$sqlmap['hb.user_id'] = array('IN',$ids);
				
			}
			if($_GET["start"]!="" or $_GET["end"]!=""){
				$start = strtotime($_GET['start'].' 00:00:00');
				$end = strtotime($_GET['end'].' 23:59:59');
				$sqlmap['hb.add_time'] =array('between',[date('Y-m-d H:i:s',$start),date('Y-m-d H:i:s',$end)]);
			}
		
			if($_GET['status']){
				$sqlmap['hb.type'] = $_GET['status'];
			}
			$data = array();
			$data['status'] = array(
				//1:回收 2:兑换3：交易（冻结或返还） 4：分红 5：中奖 6：邀请获取7：后台操作 8:投注
				array(
					'id'=>1,
					'name'=>'充值'
				),
				array(
					'id'=>2,
					'name'=>'提现'
				),
				array(
					'id'=>3,
					'name'=>'交易'
				),
				array(
					'id'=>4,
					'name'=>'兑换GF'
				),
				array(
					'id'=>5,
					'name'=>'后台操作'
				),
			);
			foreach($data['status'] as $key => $value){
				if($value['id'] == $_GET['status']) $data['status'][$key]['selected'] = true;
			}
			$_GET['pagenum'] = isset($_GET['page']) ? intval($_GET['page']) : 1;
			$_GET['rowsnum'] = isset($_GET['rows']) && (int)($_GET['rows']) != 0 ? intval($_GET['rows']) : PAGE_SIZE;
			$data['total'] = (int) M('hang_buy')->where($sqlmap)->count();
			$data['rows'] = M('balance_exchange_records hb')
						  ->join("__USER__ a on a.id=hb.user_id")
						  ->where($sqlmap)
						  ->field('hb.*,a.username')
						  ->limit(($_GET['pagenum']-1)*$_GET['rowsnum'].','.$_GET['rowsnum'])
						  ->select();
			$data['rows'] = !is_array($data['rows']) ? array() : $data['rows'];
			echo json_encode($data);
		}else{
			include $this->admin_tpl('balance1');
		}
	}
	//余额充值列表
	public function balance2(){
		if(IS_POST){
			if ($_GET['keyword']) {
				$map = array();
				$map['username'] = array('LIKE',"%".trim($_GET['keyword'])."%");
				$ids = model('user')->where($map)->getField('id',TRUE);
				$sqlmap['hb.user_id'] = array('IN',$ids);
				
			}
			if($_GET["start"]!="" or $_GET["end"]!=""){
				$start = strtotime($_GET['start'].' 00:00:00');
				$end = strtotime($_GET['end'].' 23:59:59');
				$sqlmap['hb.add_time'] =array('between',[date('Y-m-d H:i:s',$start),date('Y-m-d H:i:s',$end)]);
			}
		
			if($_GET['status']){
				$sqlmap['hb.status'] = $_GET['status'];
			}
			if($_GET['type']){
				$sqlmap['hb.type'] = $_GET['type'];
			}
			$data = array();
			$data['status'] = array(
				//1:回收 2:兑换3：交易（冻结或返还） 4：分红 5：中奖 6：邀请获取7：后台操作 8:投注
				array(
					'id'=>1,
					'name'=>'待支付'
				),
				array(
					'id'=>2,
					'name'=>'已上传未确认'
				),
				array(
					'id'=>3,
					'name'=>'已确认'
				),
				array(
					'id'=>4,
					'name'=>'驳回'
				),
				
			);
			foreach($data['status'] as $key => $value){
				if($value['id'] == $_GET['status']) $data['status'][$key]['selected'] = true;
			}
			$data['type'] = array(
				//1:回收 2:兑换3：交易（冻结或返还） 4：分红 5：中奖 6：邀请获取7：后台操作 8:投注
				array(
					'id'=>1,
					'name'=>'支付宝'
				),
				array(
					'id'=>2,
					'name'=>'银行卡'
				),

				
			);
			foreach($data['type'] as $key => $value){
				if($value['id'] == $_GET['type']) $data['type'][$key]['selected'] = true;
			}
			$_GET['pagenum'] = isset($_GET['page']) ? intval($_GET['page']) : 1;
			$_GET['rowsnum'] = isset($_GET['rows']) && (int)($_GET['rows']) != 0 ? intval($_GET['rows']) : PAGE_SIZE;
			$data['total'] = (int) M('hang_buy')->where($sqlmap)->count();
			$data['rows'] = M('chongzhi_records hb')
						  ->join("__USER__ a on a.id=hb.user_id")
						  ->where($sqlmap)
						  ->field('hb.*,a.username')
						  ->limit(($_GET['pagenum']-1)*$_GET['rowsnum'].','.$_GET['rowsnum'])
						  ->select();
			$data['rows'] = !is_array($data['rows']) ? array() : $data['rows'];
			echo json_encode($data);
		}else{
			include $this->admin_tpl('balance2');
		}
	}
	
	public function chongzhi_check(){
		if(IS_POST){
			$param = I('post.');
			if($param['status'] == 4 && !$param['remarks']){
				showmessage('请填写驳回原因');
			}
			$param['update_time'] = date('Y-m-d H:i:s');
			$param['id'] = $param['user_id'];
			unset($param['user_id']);
			try{
				M()->startTrans();

				M('chongzhi_records')->where(['id'=>$param['id']])->save($param);
				$chongzhi_info = M('chongzhi_records')->where(['id'=>$param['id']])->find();
				M('user')->where(['id'=>$chongzhi_info['user_id']])->setInc('balance',$chongzhi_info['balance']);
				$data = [
					'user_id'=>$chongzhi_info['user_id'],
					'balance'=>$chongzhi_info['balance'],
					'type'=>1,
					'remarks'=>'充值获取余额'.$chongzhi_info['balance'],
					'add_time'=>date('Y-m-d H:i:s')
				];
				M('balance_exchange_records')->add($data);

				M()->commit();
			}catch(\Exception $e){
				M()->rollback();
				showmessage($e->getMessage());
			}
			showmessage('操作成功',U('balance2'),1);
		}else{
			showmessage('非法操作');
		}
	}

	//余额提现列表
	public function balance3(){
		if(IS_POST){
			if ($_GET['keyword']) {
				$map = array();
				$map['username'] = array('LIKE',"%".trim($_GET['keyword'])."%");
				$ids = model('user')->where($map)->getField('id',TRUE);
				$sqlmap['hb.user_id'] = array('IN',$ids);
				
			}
			if($_GET["start"]!="" or $_GET["end"]!=""){
				$start = strtotime($_GET['start'].' 00:00:00');
				$end = strtotime($_GET['end'].' 23:59:59');
				$sqlmap['hb.add_time'] =array('between',[date('Y-m-d H:i:s',$start),date('Y-m-d H:i:s',$end)]);
			}
		
			if($_GET['status']){
				$sqlmap['hb.status'] = $_GET['status'];
			}
			if($_GET['type']){
				$sqlmap['hb.type'] = $_GET['type'];
			}
			$data = array();
			$data['status'] = array(
				//1:回收 2:兑换3：交易（冻结或返还） 4：分红 5：中奖 6：邀请获取7：后台操作 8:投注
				array(
					'id'=>1,
					'name'=>'已发起待确认'
				),
				
				array(
					'id'=>2,
					'name'=>'已确认'
				),
				array(
					'id'=>3,
					'name'=>'已驳回'
				),
				
			);
			foreach($data['status'] as $key => $value){
				if($value['id'] == $_GET['status']) $data['status'][$key]['selected'] = true;
			}
			$data['type'] = array(
				//1:回收 2:兑换3：交易（冻结或返还） 4：分红 5：中奖 6：邀请获取7：后台操作 8:投注
				array(
					'id'=>1,
					'name'=>'支付宝'
				),
				array(
					'id'=>2,
					'name'=>'银行卡'
				),

				
			);
			foreach($data['type'] as $key => $value){
				if($value['id'] == $_GET['type']) $data['type'][$key]['selected'] = true;
			}
			$_GET['pagenum'] = isset($_GET['page']) ? intval($_GET['page']) : 1;
			$_GET['rowsnum'] = isset($_GET['rows']) && (int)($_GET['rows']) != 0 ? intval($_GET['rows']) : PAGE_SIZE;
			$data['total'] = (int) M('hang_buy')->where($sqlmap)->count();
			$data['rows'] = M('tixian_records hb')
						  ->join("__USER__ a on a.id=hb.user_id")
						  ->where($sqlmap)
						  ->field('hb.*,a.username')
						  ->limit(($_GET['pagenum']-1)*$_GET['rowsnum'].','.$_GET['rowsnum'])
						  ->order('hb.id desc')
						  ->select();
			$data['rows'] = !is_array($data['rows']) ? array() : $data['rows'];
			echo json_encode($data);
		}else{
			include $this->admin_tpl('balance3');
		}
	}

	public function tixian_check(){
		if(IS_POST){
			$param = I('post.');
			if($param['status'] == 3 && !$param['remarks']){
				showmessage('请填写驳回原因');
				
			}elseif($param['status'] == 2){
				unset($param['remarks']);
			}
			$param['update_time'] = date('Y-m-d H:i:s');
		
			// var_dump($param);
			try{
				M()->startTrans();

				M('tixian_records')->where(['id'=>$param['id']])->save($param);
				$chongzhi_info = M('tixian_records')->where(['id'=>$param['id']])->find();
				$user_info = M('user')->where(['id'=>$chongzhi_info['user_id']])->find();
				if($param['status'] == 3){
					// M('user')->where(['id'=>$chongzhi_info['user_id']])->setInc('balance',$chongzhi_info['balance']);
					$data = [
						'user_id'=>$chongzhi_info['user_id'],
						'balance'=>+$chongzhi_info['need_pay'],
						'type'=>2,
						'remarks'=>$param['remarks'],
						'add_time'=>date('Y-m-d H:i:s')
					];
					M('balance_exchange_records')->add($data);
					$data1 = [
						'balance'=>$user_info['balance']+$chongzhi_info['need_pay'],
						'freeze_balance'=>$user_info['freeze_balance']-$chongzhi_info['need_pay']
					];
					M('user')->where(['id'=>$chongzhi_info['user_id']])->save($data1);
				}
				
				M()->commit();
			}catch(\Exception $e){
				M()->rollback();
				showmessage($e->getMessage());
			}
			showmessage('操作成功',U('balance3'),1);
		}else{
			showmessage('非法操作');
		}
	}

	public function huishou_check(){
		if(IS_POST){
			$param = I('post.');
			if($param['status'] == 3 && !$param['remarks']){
				showmessage('请填写驳回原因');
				
			}elseif($param['status'] == 2){
				unset($param['remarks']);
			}
			$param['update_time'] = date('Y-m-d H:i:s');
		
			// var_dump($param);
			try{
				M()->startTrans();

				M('huishou_records')->where(['id'=>$param['id']])->save($param);
				$chongzhi_info = M('huishou_records')->where(['id'=>$param['id']])->find();
				$user_info = M('user')->where(['id'=>$chongzhi_info['user_id']])->find();
				if($param['status'] == 3){
					// M('user')->where(['id'=>$chongzhi_info['user_id']])->setInc('upvaluation',$chongzhi_info['need_pay']);
					$data = [
						'user_id'=>$chongzhi_info['user_id'],
						'balance'=>+$chongzhi_info['need_pay'],
						'type'=>2,
						'remarks'=>$param['remarks'],
						'add_time'=>date('Y-m-d H:i:s')
					];
					M('upvaluation_exchange_records')->add($data);
					$data1 = [
						'upvaluation'=>$user_info['upvaluation']+$chongzhi_info['need_pay'],
						'freeze_upvaluation'=>$user_info['freeze_upvaluation']-$chongzhi_info['need_pay']
					];
					M('user')->where(['id'=>$chongzhi_info['user_id']])->save($data1);
				}
				
				M()->commit();
			}catch(\Exception $e){
				M()->rollback();
				showmessage($e->getMessage());
			}
			showmessage('操作成功',U('upvaluation2'),1);
		}else{
			showmessage('非法操作');
		}
	}
}